class Admin::FixedCostsController < ApplicationController
  before_action :get_studios, only: [:index, :new, :edit, :show]
  before_action :authorize_finance
  
  layout 'admin'
  def index
    studio_ids = @studios.map { |s| s.id }
    @fixed_costs = FixedCost.joins(:studios).where("studios.id in (#{studio_ids.join(',')})")
      .order("created_at desc")
    .paginate(page: params[:page], per_page: 10)
  end

  def new
    @fixed_cost = FixedCost.new()
  end

  def create
    @fixed_cost = FixedCost.new(fixed_cost_params)
    if @fixed_cost.save
      @fixed_cost.studio_ids = params[:studio_ids].split(",")
      @flag = true
      @message = "创建固定成本成功"
    else
      @flag = false
      @message = "创建失败！ 请检查后重新提交"
    end
    p @message
  end

  def edit
    @fixed_cost = FixedCost.find(params[:id])
    @studio_ids = @fixed_cost.studios.map {|s| s.id}
  end

  def update
    @fixed_cost = FixedCost.find(params[:id])
    if @fixed_cost.update(fixed_cost_params)
      @fixed_cost.studio_ids = params[:studio_ids].split(",")
      @flag = true
      @message = "编辑固定成本成功"
    else
      @flag = false
      @message = "编辑失败！ 请检查后重新提交"
    end
  end

  def destroy
    @fixed_cost = FixedCost.find(params[:id])
    @fixed_cost.disabled = true
    @fixed_cost.save
    @fixed_cost.destroy
    respond_to do |format|
      format.html  { redirect_to admin_fixed_costs_path }
    end
  end

  private

  def get_studios
    @company = current_company
    @studios = @company.studios
  end

  def fixed_cost_params
    params.require(:fixed_cost).permit(:name, :amount,:cycle)
  end

  def authorize_finance
    authorize Finance,:index?
  end
end
